﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;

namespace Gist
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //path, rect, downloadComplete?
        private Dictionary<string, Tuple<Rect, bool>> imageFileList;
        private DrawingGroup gistGroup;

        public MainWindow()
        {
            InitializeComponent();
            gistGroup = new DrawingGroup();
            imageFileList = new Dictionary<string, Tuple<Rect, bool>>();
            downloadProgress.Visibility = Visibility.Hidden;
        }

        private void makeGist_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.gistSearchText.Text))
            {
                MessageBox.Show("The search text must contain a value");
                return;
            }


            // Create a Bing container. 
            string rootUri = "https://api.datamarket.azure.com/Bing/Search";
            var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));

            var accountKey = "";
            
            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);

            // Build the query. 
            var imageQuery = bingContainer.Image(this.gistSearchText.Text, null, null, "Moderate", null, null, null);
            var imageResults = imageQuery.Execute();

            foreach (var result in imageResults)
            {
                try
                {
                    string tempPath = System.IO.Path.GetTempPath();
                    Uri media = new Uri(result.MediaUrl);
                    tempPath += System.IO.Path.GetFileName(media.LocalPath);

                    if (!imageFileList.ContainsKey(tempPath))
                    {
                        WebClient client = new WebClient();

                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);
                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
  
                        client.DownloadFileAsync(media, tempPath);

                        System.Windows.Size s = new System.Windows.Size();
                        s.Height = (double)result.Height;
                        s.Width = (double)result.Width;
                        Rect r = new Rect(s);

                        imageFileList.Add(tempPath, Tuple.Create(r, false));
                    }
                }
                catch (WebException ex)
                {
                    MessageBox.Show(ex.Message, "Error " + ex.Response);
                }
            } 
        }

        private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            var total = e.TotalBytesToReceive;
            var percentage = e.ProgressPercentage;
            var received = e.BytesReceived;

            this.downloadProgress.Visibility = Visibility.Visible;
            this.downloadProgress.Value = e.ProgressPercentage;
        }

        private void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
        {
            this.downloadProgress.Visibility = Visibility.Hidden;

            foreach (var file in imageFileList)
            {
                Uri u = new Uri(file.Key);
                Rect r = file.Value.Item1;
                
                BitmapImage b = null;

                try
                {
                    b = new BitmapImage(u);
                }
                catch (IOException ex)
                {
                    continue;
                }

                imageFileList.Remove(file.Key);

                ColorMatrix cmx = new ColorMatrix();
                cmx.Matrix33 = 0.5f;
                ImageAttributes attrib = new ImageAttributes();
                attrib.SetColorMatrix(cmx, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                // Graphics gfx = Graphics.FromImage(b);

                /*
                 *  Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);
     Graphics gfxPic = Graphics.FromImage(bmpPic);

     ColorMatrix cmxPic = new ColorMatrix();   
     cmxPic.Matrix33 = imgOpac;   
     ImageAttributes iaPic = new ImageAttributes();   
     iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);  
     gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);  
     gfxPic.Dispose();            

     return bmpPic;  
}
                 */
                //http://stackoverflow.com/questions/4779027/changing-the-opacity-of-a-bitmap-image
                ImageDrawing id = new ImageDrawing(b, r);
                gistGroup.Children.Add(id);
            }

            gistGroup.Opacity = 0.5f;
            gistImage.Source = new DrawingImage(gistGroup);
        }
    }
}
